package controller;

import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import beans.LogEnum;
import beans.RunningTask;
import dao.HistoryTaskDao;
import engine.BIEngine0_1.TaskThread;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import utils.UserLogUtil;

/**
 * Servlet implementation class StopTask
 */
public class StopTask extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public StopTask() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获取userId
		String userId = (String) request.getSession().getAttribute("userId");
		String taskHash = request.getParameter("taskHash");
		List<Object> taskHashes = new HistoryTaskDao().getSubTaskHashByBatchTaskHash(taskHash).getDatas();
		JSONArray resultArray = new JSONArray();
		if(taskHashes.size()<1){
			response.getWriter().write("error");
		}else{
			for(Object one:taskHashes){
				TaskThread task = RunningTask.TASKMAP.getTask((String) one);
				JSONObject oneResult = new JSONObject();
				if (task == null) {
					oneResult.put(one,"error");
				} else {
					String newestAlgorithm = task.runningTaskBean.getNewestAlgorithm();
					if(newestAlgorithm!=null){
						boolean result = task.stopTask();
						if(result){
							oneResult.put(one,"true");
							RunningTask.TASKMAP.removeTask((String)one);
						}else{
							oneResult.put(one,"error");
						}
					}else{
						oneResult.put(one, "finished");
					}
				}
				resultArray.add(oneResult);
			}
			JSONObject result = new JSONObject();
			result.put("result",resultArray);
			//将该任务hash作为父任务hash传回去
			result.put("fatherTaskHash",taskHash);
			response.getWriter().write(resultArray.toString());
			// 日志记录
			UserLogUtil.dbLog(LogEnum.historyTask, LogEnum.stopHistoryTask,
					userId, LogEnum.historyTask.getValue()+"哈希值："+taskHash);
		}
	}

}
